package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UserNameExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.commons.lang.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) throws UserNameExistException, PhoneExistException {
        // 设置默认登记
        MemberEntity entity = new MemberEntity();
        MemberLevelEntity level = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        entity.setLevelId(level.getId());

        // 用户名、手机号  是否唯一
        checkUserNameExist(vo.getUserName());
        checkPhoneExist(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setMobile(vo.getPhone());

        // 密码加密
        // 自动加盐值， 自动解析
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);


        this.baseMapper.insert(entity);
    }

    @Override
    public void checkUserNameExist(String userName) throws UserNameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count>0){
            throw new UserNameExistException();
        }
    }

    @Override
    public void checkPhoneExist(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile",phone));
        if (count>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberEntity vo) {
        MemberEntity one = this.getOne(new QueryWrapper<MemberEntity>().eq("username", vo.getUsername()).or().eq("mobile", vo.getUsername()));
        if (one == null){
            // 账号不存在
            return null;
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(vo.getPassword(), one.getPassword());
        if (matches) {
            // 验证通过
            return one;
        }
        return null;
    }


    @Override
    public MemberEntity login(SocialUser user) throws Exception {


        // 用户的uid是唯一的
//        判断是登录还是注册
        String uid = user.getUid();
        MemberEntity one = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (one!=null){
            // 登录
            MemberEntity entity = new MemberEntity();
            entity.setId(one.getId());
            entity.setLevelId(1l);
            entity.setAccessToken(user.getAccess_token());
            entity.setExpiresIn(String.valueOf(user.getExpires_in()));
            this.baseMapper.updateById(entity);

            one.setAccessToken(user.getAccess_token());
            one.setExpiresIn(String.valueOf(user.getExpires_in()));
            return one;
        }else {
            // 注册
            MemberEntity register = new MemberEntity();
            // 获取weibo用户信息
            HashMap<String, String> query = new HashMap<>();
            query.put("access_token", user.getAccess_token());
            query.put("uid",uid);

            /**
             * 这个位置要具体修改 ， 因为现在我的weibo开发认证还未通过。
             */
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show", "get", query, query);
            if (response.getStatusLine().getStatusCode() == 200){
                // 查询成功
                String string = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(string);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                // ....
                register.setNickname(name);
                register.setGender("m".equals(gender)?1:0);

                register.setAccessToken(user.getAccess_token());
                register.setSocialUid(user.getUid());
                register.setExpiresIn(String.valueOf(user.getExpires_in()));

                this.baseMapper.insert(register);

                return register;
            }

        }
        return null;
    }

}